package com.ruoyi.project.modules.frontInterfaceFieldSource.controller;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysDictType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.modules.category.domain.Category;
import com.ruoyi.project.modules.fileInfo.domain.FileInf;
import com.ruoyi.project.modules.fileInfo.service.IFileInfoService;
import com.ruoyi.project.modules.interfaceObject.domain.InterfaceObject;
import com.ruoyi.project.modules.interfaceObject.service.IInterfaceObjectService;
import com.ruoyi.project.modules.interfaceinfo.domain.InterfaceInfo;
import com.ruoyi.project.modules.interfaceinfo.domain.VirtualUsage;
import com.ruoyi.project.modules.interfaceinfo.service.IInterfaceInfoService;
import com.ruoyi.project.modules.interfaceinfo.vo.InterfaceParam;
import com.ruoyi.project.modules.page.domain.Page;
import com.ruoyi.project.modules.page.service.IPageService;
import com.ruoyi.project.modules.parameter.domain.InterfaceParamsFieldRelation;
import com.ruoyi.project.modules.parameter.domain.ParamsFieldRelation;
import com.ruoyi.project.modules.parameter.service.IInterfaceParamsFieldRelationService;
import com.ruoyi.project.modules.parameter.service.IParamsFieldRelationService;
import com.ruoyi.project.modules.table.domain.FieldInfo;
import com.ruoyi.project.modules.table.domain.TableInfo;
import com.ruoyi.project.modules.table.service.ITableInfoService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.project.modules.frontInterfaceFieldSource.domain.FrontInterfaceFieldSource;
import com.ruoyi.project.modules.frontInterfaceFieldSource.service.IFrontInterfaceFieldSourceService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 前端接口字段来源Controller
 *
 * @author smallrain
 * @date 2022-05-03
 */
@Controller
@RequestMapping("/frontInterfaceFieldSource/frontInterfaceFieldSource")
@Api(tags = "前端接口字段来源")
public class FrontInterfaceFieldSourceController extends BaseController {
    private String prefix = "frontInterfaceFieldSource/frontInterfaceFieldSource";

    @Autowired
    private IFrontInterfaceFieldSourceService frontInterfaceFieldSourceService;

    //@RequiresPermissions("frontInterfaceFieldSource:frontInterfaceFieldSource:view")
    @GetMapping()
    public String frontInterfaceFieldSource() {
        return prefix + "/frontInterfaceFieldSource";
    }

    /**
     * 查询前端接口字段来源列表
     */
    //@RequiresPermissions("frontInterfaceFieldSource:frontInterfaceFieldSource:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(FrontInterfaceFieldSource frontInterfaceFieldSource) {
        startPage();
        List<FrontInterfaceFieldSource> list = frontInterfaceFieldSourceService.selectFrontInterfaceFieldSourceList(frontInterfaceFieldSource);
        return getDataTable(list);
    }

    /**
     * 导出前端接口字段来源列表
     */
    //@RequiresPermissions("frontInterfaceFieldSource:frontInterfaceFieldSource:export")
    @Log(title = "前端接口字段来源", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(FrontInterfaceFieldSource frontInterfaceFieldSource) {
        List<FrontInterfaceFieldSource> list = frontInterfaceFieldSourceService.selectFrontInterfaceFieldSourceList(frontInterfaceFieldSource);
        ExcelUtil<FrontInterfaceFieldSource> util = new ExcelUtil<FrontInterfaceFieldSource>(FrontInterfaceFieldSource.class);
        return util.exportExcel(list, "前端接口字段来源数据");
    }

    /**
     * 新增前端接口字段来源
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存前端接口字段来源
     */
    //@RequiresPermissions("frontInterfaceFieldSource:frontInterfaceFieldSource:add")
    @Log(title = "前端接口字段来源", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(FrontInterfaceFieldSource frontInterfaceFieldSource) {
        return toAjax(frontInterfaceFieldSourceService.insertFrontInterfaceFieldSource(frontInterfaceFieldSource));
    }

    /**
     * 修改前端接口字段来源
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        FrontInterfaceFieldSource frontInterfaceFieldSource = frontInterfaceFieldSourceService.selectFrontInterfaceFieldSourceById(id);
        mmap.put("frontInterfaceFieldSource", frontInterfaceFieldSource);
        return prefix + "/edit";
    }

    /**
     * 修改保存前端接口字段来源
     */
    //@RequiresPermissions("frontInterfaceFieldSource:frontInterfaceFieldSource:edit")
    @Log(title = "前端接口字段来源", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(FrontInterfaceFieldSource frontInterfaceFieldSource) {
        return toAjax(frontInterfaceFieldSourceService.updateFrontInterfaceFieldSource(frontInterfaceFieldSource));
    }

    /**
     * 删除前端接口字段来源
     */
    //@RequiresPermissions("frontInterfaceFieldSource:frontInterfaceFieldSource:remove")
    @Log(title = "前端接口字段来源", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(frontInterfaceFieldSourceService.deleteFrontInterfaceFieldSourceByIds(ids));
    }

    @Autowired
    private IInterfaceInfoService interfaceInfoService;

    @Autowired
    private IInterfaceObjectService interfaceObjectService;

    @Autowired
    private IInterfaceParamsFieldRelationService interfaceParamsFieldRelationService;

    @Autowired
    private IParamsFieldRelationService paramsFieldRelationService;

    @Autowired
    private ITableInfoService tableInfoService;

    @Autowired
    private ISysDictTypeService sysDictTypeService;

    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private IPageService pageService;

    /**
     * 查询接口字段来源详情
     * @author chenxiaoyu
     * @date 2022/5/4 上午12:49
     * @param pageId 页面id
     * @param pageImgId 页面图片id
     * @param interfaceFieldId 接口字段id
     * @param type 1-字段 2-数据集字段
     * @return com.ruoyi.common.core.domain.AjaxResult
     */
    @GetMapping("/detail")
    @ResponseBody
    public AjaxResult detail(@RequestParam("id") Long pageId,@RequestParam("pageImgId") Long pageImgId,@RequestParam("interfaceFieldId") Long interfaceFieldId,@RequestParam("type") String type) {
        FrontInterfaceFieldSource frontInterfaceFieldSource = new FrontInterfaceFieldSource();
        frontInterfaceFieldSource.setPageId(pageId);
        frontInterfaceFieldSource.setPageImgId(pageImgId);
        frontInterfaceFieldSource.setObjectId(interfaceFieldId);
        frontInterfaceFieldSource.setObjectType(type);
        List<FrontInterfaceFieldSource> frontInterfaceFieldSources = frontInterfaceFieldSourceService.selectFrontInterfaceFieldSourceList(frontInterfaceFieldSource);
        if (CollectionUtil.isNotEmpty(frontInterfaceFieldSources)) {
            return AjaxResult.success(frontInterfaceFieldSources.get(0));
        }
        return AjaxResult.success(new FrontInterfaceFieldSource());
    }

    /**
     * 根据页面id或者storageType，查询页面关联接口
     * @author chenxiaoyu
     * @date 2022/5/3 下午11:28
     * @param pageId 页面id （必填）
     * @param storageType local-localStorage all-全局Storage page-页面 (非必填)
     * @return com.ruoyi.common.core.domain.AjaxResult
     */
    @GetMapping("/queryInterfaceByPageId")
    @ResponseBody
    public AjaxResult queryInterfaceByPageIdOrStorageType(@RequestParam Long pageId,@RequestParam(required = false) String storageType) {
        if (storageType != null && !"page".equals(storageType)) {
            InterfaceInfo interfaceInfo = new InterfaceInfo();
            interfaceInfo.setFbType("2");
            interfaceInfo.setStorageType(storageType);
            List<InterfaceInfo> interfaceInfoList = this.interfaceInfoService.selectInterfaceInfoList(interfaceInfo);
            return AjaxResult.success(interfaceInfoList);
        } else {
            Page page = this.pageService.selectPageById(pageId);
            Page page1 = new Page();
            page1.setCategoryId(page.getCategoryId());
            List<Page> pageList = this.pageService.selectPageList(page1);
            List<Long> pageIds = pageList.stream().map(Page::getId).collect(Collectors.toList());
            InterfaceObject interfaceObject = new InterfaceObject();
            interfaceObject.setObjectType("2");
            interfaceObject.setTableIds(pageIds);
            List<InterfaceObject> interfaceObjectList = this.interfaceObjectService.selectInterfaceObjectList(interfaceObject);
            if (CollectionUtil.isNotEmpty(interfaceObjectList)) {
                List<Long> ids = interfaceObjectList.stream().map(InterfaceObject::getInterfaceId).collect(Collectors.toList());
                InterfaceInfo interfaceInfo = new InterfaceInfo();
                interfaceInfo.setIds(ids);
                List<InterfaceInfo> interfaceInfoList = this.interfaceInfoService.selectInterfaceInfoList(interfaceInfo);
                return AjaxResult.success(interfaceInfoList);
            }
        }
        return AjaxResult.success(new ArrayList<>());
    }

    /**
     * 查询bff接口出参或者入参
     * 响应数据：
     * [{
     *     id:1,
     *     fieldName:'测试'，
     *     fieldEnName:'test'
     * }, {
     *     id:2,
     *     fieldName:'测试2'，
     *     fieldEnName:'test2',
     *     children:[{
     *          id:21,
     *          fieldName:'测试21'，
     *          fieldEnName:'test21'
     *     }]
     * }]
     * @author chenxiaoyu
     * @date 2022/5/3 下午11:31
     * @param interfaceId 接口id
     * @param isInParam 1-出参 2-入参
     * @return com.ruoyi.common.core.domain.AjaxResult
     */
    @GetMapping("/queryBffInterfaceField")
    @ResponseBody
    public AjaxResult queryBffInterfaceField(@RequestParam Long interfaceId, @RequestParam String isInParam, @RequestParam(required = false) Long pageId, @RequestParam(required = false) Long pageImageId) {
        List<InterfaceParam> interfaceParams = this.interfaceInfoService.paramList("2", interfaceId, isInParam);
        if ("1".equals(isInParam) && CollectionUtil.isNotEmpty(interfaceParams)) {
            // 查询前端入参来源
            if (pageId != null && pageImageId != null) {
                FrontInterfaceFieldSource frontInterfaceFieldSource = new FrontInterfaceFieldSource();
                frontInterfaceFieldSource.setPageId(pageId);
                frontInterfaceFieldSource.setPageImgId(pageImageId);
                frontInterfaceFieldSource.setInterfaceId(interfaceId);
                List<FrontInterfaceFieldSource> frontInterfaceFieldSources = this.frontInterfaceFieldSourceService.selectFrontInterfaceFieldSourceList(frontInterfaceFieldSource);
                if (CollectionUtil.isNotEmpty(frontInterfaceFieldSources)) {
                    Map<String, FrontInterfaceFieldSource> map = new HashMap<>();
                    for (FrontInterfaceFieldSource interfaceFieldSource : frontInterfaceFieldSources) {
                        map.put(interfaceFieldSource.getObjectId() + interfaceFieldSource.getObjectType(), interfaceFieldSource);
                    }

                    handlerFrontFieldSource(interfaceParams, "1", map);
                }
            }
        }
        return AjaxResult.success(interfaceParams);
    }


    private void handlerFrontFieldSource(List<InterfaceParam> requestList, String type, Map<String, FrontInterfaceFieldSource> map) {
        List<SysDictData> sysDictDataList = sysDictTypeService.selectDictDataByType("storageType");
        Map<String, List<SysDictData>> collect = sysDictDataList.stream().collect(Collectors.groupingBy(SysDictData::getDictValue));
        for (InterfaceParam interfaceParam : requestList) {
            FrontInterfaceFieldSource fieldSource = map.get(interfaceParam.getId() + type);
            if (fieldSource != null) {
                interfaceParam.setFrontFieldRemark(fieldSource.getRemark());
                StringBuilder fieldSourceStr = new StringBuilder("来源于");
                if (fieldSource.getSourceType().equals("1")) {
                    String aliasName = null;
                    if (fieldSource.getSourcePageImgId() != null && fieldSource.getSourcePageImgId() > 0) {
                        FileInf fileInf = this.fileInfoService.selectFileInfoById(fieldSource.getSourcePageImgId());
                        aliasName = fileInf.getAliasName();
                        if (StringUtils.isNotEmpty(aliasName)) {
                            aliasName = "(" + aliasName + ")";
                        }
                    }

                    fieldSourceStr.append("接口 ").append(fieldSource.getSourceInterfaceName() + "(" +fieldSource.getSourceInterfaceUrl() + ")");
//                    if (StringUtils.isNotEmpty(aliasName)) {
//                        fieldSourceStr.append(aliasName);
//                    }
                    if (StringUtils.isNotEmpty(fieldSource.getSourceObjectFieldName())) {
                        fieldSourceStr.append(" 的数据集").append(fieldSource.getSourceObjectName() + "(" + fieldSource.getSourceObjectEnName() +")").append("下字段").append(fieldSource.getSourceObjectFieldName() + "(" + fieldSource.getSourceObjectFieldEnName() +")");
                    } else {
                        fieldSourceStr.append(" 的字段").append(fieldSource.getSourceObjectName() + "(" + fieldSource.getSourceObjectEnName() +")");
                    }

                    if ("Y".equals(fieldSource.getIsPageStore())) {
                        fieldSourceStr.append(" 是页面store");
                    }
                    if (StringUtils.isNotEmpty(fieldSource.getSourceDictType())) {
                        fieldSourceStr.append("，此处出参默认值：");
                    }
                    fieldSourceStr.append(this.getDictValueName(fieldSource.getSourceDictType(), fieldSource.getSourceDictValue()));

                } else if (fieldSource.getSourceType().equals("2")) {
                    fieldSourceStr.append("约定值 ");
                    if (fieldSource.getContractValueType().equals("0")) {
                        fieldSourceStr.append("类型").append(fieldSource.getDictType());
                        if (StringUtils.isNotEmpty(fieldSource.getDictValue())) {
                            fieldSourceStr.append("(").append(fieldSource.getDictValue()).append(")");
                        }
                    } else if (fieldSource.getContractValueType().equals("1")) {
                        fieldSourceStr.append("类型编码").append(fieldSource.getDictValue());
                    } else if (fieldSource.getContractValueType().equals("2")) {
                        fieldSourceStr.append("关联表名").append(fieldSource.getTableOrFieldName());
                    } else if (fieldSource.getContractValueType().equals("3")) {
                        fieldSourceStr.append("关联表主键名").append(fieldSource.getTableOrFieldName());
                    } else if (fieldSource.getContractValueType().equals("4")) {
                        fieldSourceStr.append("对象属性code ");
                        if (fieldSource.getSourceObjectFieldName() != null) {
                            fieldSourceStr.append("数据集").append(fieldSource.getSourceObjectName()).append("下字段").append(fieldSource.getSourceObjectFieldName());
                        } else {
                            fieldSourceStr.append("字段").append(fieldSource.getSourceObjectName());
                        }
                    } else if (fieldSource.getContractValueType().equals("5")) {
                        fieldSourceStr.append("固定值 ").append(fieldSource.getContractValue());
                    } else if (fieldSource.getContractValueType().equals("6")) {
                        fieldSourceStr.append("主键标识 ").append(this.getDictName(fieldSource.getDictType())).append(this.getDictValueName(fieldSource.getDictType(), fieldSource.getDictValue()));
                    }
                } else if (fieldSource.getSourceType().equals("3")) {
                    List<SysDictData> sysDictData = collect.get(fieldSource.getStorageType());
                    fieldSourceStr.append("前端本地 " + sysDictData.get(0).getDictLabel() + "中接口 ").append(fieldSource.getSourceInterfaceName() + "(" +fieldSource.getSourceInterfaceUrl() + ")");
                    if (StringUtils.isNotEmpty(fieldSource.getSourceObjectFieldName())) {
                        fieldSourceStr.append(" 的数据集").append(fieldSource.getSourceObjectName() + "(" + fieldSource.getSourceObjectEnName() +")").append("下字段").append(fieldSource.getSourceObjectFieldName() + "(" + fieldSource.getSourceObjectFieldEnName() +")");
                    } else {
                        fieldSourceStr.append(" 的字段").append(fieldSource.getSourceObjectName() + "(" + fieldSource.getSourceObjectEnName() +")");
                    }
                }
                interfaceParam.setFrontFieldSource(fieldSourceStr.toString());
            }
            if (CollectionUtil.isNotEmpty(interfaceParam.getChildren())) {
                this.handlerFrontFieldSource(interfaceParam.getChildren(), "2", map);
            }
        }
    }

    private String getDictName(String dictType) {
        if (StringUtils.isNotEmpty(dictType)) {
            SysDictType sysDictType = this.sysDictTypeService.selectDictTypeByType(dictType);
            if (sysDictType != null) {
                return sysDictType.getDictName() + "(" + sysDictType.getDictType() + ")";
            }
        }
        return "";
    }

    private String getDictValueName(String dictType, String dictValue) {
        if (StringUtils.isNotEmpty(dictType) && StringUtils.isNotEmpty(dictValue)) {
            List<SysDictData> sysDictData = this.sysDictTypeService.selectDictDataByType(dictType);
            if (CollectionUtil.isNotEmpty(sysDictData)) {
                for (SysDictData sysDictType : sysDictData) {
                    if (sysDictType.getDictValue().equals(dictValue)) {
                        return sysDictType.getDictLabel() + "(" + sysDictType.getDictValue() +")";
                    }
                }
            }
        }
        return "";
    }
    /** 
     * 查询字典编码
     * return:
     * [{
     *     dictName:'xxx',//字典名称
     *     dictType:'xxx'// 字典类型
     * }]
     * @author chenxiaoyu
     * @date 2022/5/8 下午11:45
     * @return com.ruoyi.common.core.domain.AjaxResult
     */ 
    @GetMapping("/queryDictType")
    @ResponseBody
        public AjaxResult queryDictType() {
        List<SysDictType> sysDictTypeList = this.frontInterfaceFieldSourceService.queryDictType();
        return AjaxResult.success(sysDictTypeList);
    }


    /** 
     * 根据接口字段id，查询类型编码（字典）
     * @author chenxiaoyu
     * @date 2022/5/3 下午11:37
     * @param interfaceFieldId 接口字段id
     * @param type 1-字段id 2-数据集字段id
     * @return com.ruoyi.common.core.domain.AjaxResult
     */ 
    @GetMapping("/queryFieldDict")
    @ResponseBody
    public AjaxResult queryFieldDict(@RequestParam Long interfaceFieldId, @RequestParam String type) {
        Long fieldId = null;
        if ("1".equals(type)) {
            InterfaceParamsFieldRelation interfaceParamsFieldRelation = this.interfaceParamsFieldRelationService.selectInterfaceParamsFieldRelationById(interfaceFieldId);
            fieldId = interfaceParamsFieldRelation.getObjectId();
        } else {
            ParamsFieldRelation paramsFieldRelation = this.paramsFieldRelationService.selectParamsFieldRelationById(interfaceFieldId);
            fieldId = paramsFieldRelation.getFieldId();
        }
        List<FieldInfo> fieldInfoList = this.tableInfoService.selectFieldInfoByFieldId(Arrays.asList(fieldId));
        if (CollectionUtil.isNotEmpty(fieldInfoList)) {
            FieldInfo fieldInfo = fieldInfoList.get(0);
            if ("Y".equals(fieldInfo.getIsFieldEnum()) && fieldInfo.getDictId() != null) {
                SysDictType sysDictType = this.sysDictTypeService.selectDictTypeById(fieldInfo.getDictId());
                if (sysDictType != null) {
                    SysDictData dictData = new SysDictData();
                    dictData.setDictType(sysDictType.getDictType());
                    List<SysDictData> sysDictData = this.sysDictDataService.selectDictDataList(dictData);
                    return AjaxResult.success(sysDictData);
                }
            }
        }
        return AjaxResult.success(new ArrayList<>());
    }

    /**
     * 查询表信息列表
     * @author chenxiaoyu
     * @date 2022/5/4 上午12:39
     * @param keyword 关键字
     * @return com.ruoyi.common.core.domain.AjaxResult
     */
    @GetMapping("/tableList")
    @ResponseBody
    public AjaxResult tableList(@RequestParam(required = false) String keyword) {
        TableInfo tableInfo = new TableInfo();
        tableInfo.setSearchValue(keyword);
        List<TableInfo> tableInfos = this.tableInfoService.selectTableInfoList(tableInfo);
        return AjaxResult.success(tableInfos);
    }

    /**
     * 查询主键列表
     * @author chenxiaoyu
     * @date 2022/5/4 上午12:40
     * @param keyword 关键字
     * @return com.ruoyi.common.core.domain.AjaxResult
     */
    @GetMapping("/pkFieldList")
    @ResponseBody
    public AjaxResult pkFieldList(@RequestParam(required = false) String keyword) {
        FieldInfo fieldInfo = new FieldInfo();
        fieldInfo.setFieldType("1");
        fieldInfo.setSearchValue(keyword);
        List<FieldInfo> fieldInfoList = this.tableInfoService.queryFieldInfoList(fieldInfo);
        return AjaxResult.success(fieldInfoList);
    }

    /**
     * 查询字典数据
     * @author chenxiaoyu
     * @date 2022/5/4 上午9:58
     * @param dictType 字典类型
     * @return com.ruoyi.common.core.domain.AjaxResult
     */
    @PostMapping("/queryDict")
    @ResponseBody
    @ApiOperation("根据字典类型，查询数据")
    public AjaxResult queryDict(String dictType) {
        List<SysDictData> sysDictData = this.sysDictTypeService.selectDictDataByType(dictType);
        return AjaxResult.success(sysDictData);
    }

    /**
     * 保存或者更新字段来源设置
     * eg: {
     *     "id":1, // 更新时，必填
     *     "pageId":1, // 页面id
     *     "pageImgId":1, // 页面图片id
     *     "interfaceId":1, // 接口id
     *     "objectType":"1", // 1-字段 2-数据集字段
     *     "objectId":1, // 字段或者数据集字段id
     *     "sourceType":"1", // 来源类型：1-来源接口 2-来源约定值 3-来源前端本地
     *     "sourceInterfaceId":1, // 来源接口id
     *     "sourceInterfaceUrl":'/login', // 来源接口地址
     *     "sourceInterfaceName":'/login', // 来源接口名称
     *     "isPageStore":'Y',// 是否页面store （Y-是 N-否）
     *     "sourceObjectId":1, // 来源字段（数据集）id
     *     "sourceObjectName":field', // 来源字段（数据集）名称
     *     "sourceObjectEnName":field', // 来源字段（数据集）英文名称
     *     "sourceObjectFieldId":1, //来源数据集字段id（当选择数据集时，必填）
     *     "sourceObjectFieldName":'xxx', //来源数据集字段名称（当选择数据集时，必填）
     *     "sourceObjectFieldEnName":'xxx', //来源数据集字段英文名称（当选择数据集时，必填）
     *     "contractValueType":'1', //约定值类型（0-类型 1-类型编码 2-关联表名 3-关联表主键名 4-对象属性code 5-对象属性值（固定值） 6-主键标识
     *     "dictType":"yesOrNo",// 类型（当约定值类型是 0时，必填）
     *     "dictValue":'1', //字典值 （当约定值类型是 1时，必填）
     *     "tableOrFieldId":'1', //表id或者主键字段id （当约定值类型是 2、3时，必填）
     *     "tableOrFieldName":1, //表或者主键字段英文名称
     *     "contractValue":1, //自定义约定值
     *     "storageType":'page', //页面存储页面(字典) page-页面 local-localStorage all-全局storage...
     *     "sourcePageImgId": 1, // 来源页面图片id
     *     "dictCategory":2, // 约定值类型是0 必填 字典分类
     *     "sourceDictType":"", // 来源接口的入参的所有类型
     *     "sourceDictValue":"" // 根据第一个下拉选择的类型，选择类型下具体的某一个字典值
     * }
     * @author chenxiaoyu
     * @date 2022/5/4 上午10:48
     * @param frontInterfaceFieldSource 请求数据
     * @return com.ruoyi.common.core.domain.AjaxResult
     */
    @PostMapping("/saveFieldSource")
    @ResponseBody
    public AjaxResult saveFieldSource(@RequestBody FrontInterfaceFieldSource frontInterfaceFieldSource) {
        if (frontInterfaceFieldSource.getId() == null) {
            return toAjax(frontInterfaceFieldSourceService.insertFrontInterfaceFieldSource(frontInterfaceFieldSource));
        } else {
            return toAjax(frontInterfaceFieldSourceService.updateFrontInterfaceFieldSource(frontInterfaceFieldSource));
        }
    }

    @Autowired
    private IFileInfoService fileInfoService;

    /**
     * 根据接口id和页面id，返回在页面所有关于这个接口的别名集合
     * response:
     * [{
     *     id:1,
     *     aliasName:'xxxx'
     * },{
     *      id:2,
     *      aliasName:'xxxxxx'
     *  }]
     * @param pageId
     * @param interfaceId
     * @return
     */
    @GetMapping("/queryInterfaceAliasNames")
    @ResponseBody
    @ApiOperation("根据接口id和页面id，返回在页面所有关于这个接口的别名集合")
    public AjaxResult queryInterfaceAliasNames(Long pageId, Long interfaceId) {
        Page page = this.pageService.selectPageById(pageId);
        Page page1 = new Page();
        page1.setCategoryId(page.getCategoryId());
        List<Page> pageList = this.pageService.selectPageList(page1);
        List<Long> pageIds = pageList.stream().map(Page::getId).collect(Collectors.toList());

        FileInf fileInf = new FileInf();
        fileInf.setImgType(null);
        fileInf.setIsMaster(null);
        fileInf.setObjectType("2");
        fileInf.setObjectIds(pageIds);
        List<FileInf> fileInfs = this.fileInfoService.selectFileInfoList(fileInf);
        if (CollectionUtil.isNotEmpty(fileInfs)) {
            List<Long> parentIds = fileInfs.stream().map(FileInf::getId).collect(Collectors.toList());
            fileInf.setObjectType("1");
            fileInf.setIsMaster("Y");
            fileInf.setObjectId(interfaceId);
            fileInf.setParentIds(parentIds);
            fileInf.setObjectIds(null);
            fileInfs = this.fileInfoService.selectFileInfoList(fileInf);
            if (fileInfs != null && fileInfs.size() < 2) {
                fileInfs = new ArrayList<>();
            }
         }

        if (CollectionUtil.isNotEmpty(fileInfs)) {
            for (FileInf inf : fileInfs) {
                String aliasName = inf.getAliasName();
                if (StringUtils.isNotEmpty(aliasName) && aliasName.indexOf("(/oms") > 0) {
                    aliasName = aliasName.substring(0, aliasName.indexOf("(/oms"));
                }
                inf.setAliasName(aliasName);
            }
        }
        return AjaxResult.success(fileInfs);
    }

    /**
     * 获取字典分类
     * @author chenxiaoyu
     * @date 2022/6/21 下午8:32
     * @param
     * @return com.ruoyi.common.core.domain.AjaxResult
     */
    @GetMapping("/getDictCategory")
    @ApiOperation("获取字典分类")
    @ResponseBody
    public AjaxResult getCategoryDict() {
        List<SysDictData> dataDictionary = this.sysDictTypeService.selectDictDataByType("dataDictionary");
        List<SysDictData> result = new ArrayList<>();
        for (SysDictData sysDictData : dataDictionary) {
            if ("1".equals(sysDictData.getDictValue())) {
                continue;
            }
            result.add(sysDictData);
        }
        return AjaxResult.success(result);
    }

    @GetMapping("/getDictListByCategory")
    @ApiOperation("根据分类获取字典列表")
    @ResponseBody
    public AjaxResult getCategoryDict(String category) {
        SysDictType dictType = new SysDictType();
        dictType.setCategory(category);
        List<SysDictType> sysDictTypeList = this.sysDictTypeService.selectDictTypeList(dictType);
        return AjaxResult.success(sysDictTypeList);
    }

    /** https://nptxsylfsf.feishu.cn/docx/doxcn6V1cG3NgLD5dMT9kEJumbf */

    @GetMapping("/getImgInterfaceAliasName")
    @ApiOperation("查询图片接口的别名")
    @ResponseBody
    public AjaxResult getImgInterfaceAliasName(Long pageImgId) {
        FileInf fileInf = this.fileInfoService.selectFileInfoById(pageImgId);
        return AjaxResult.success(fileInf.getAliasName());
    }

    @PostMapping("/updateImgInterfaceAliasName")
    @ApiOperation("更新图片接口的别名")
    @ResponseBody
    public AjaxResult updateImgInterfaceAliasName(Long pageImgId, String aliasName) {
        FileInf fileInf = new FileInf();
        fileInf.setImgType(null);
        fileInf.setIsMaster(null);
        fileInf.setId(pageImgId);
        fileInf.setAliasName(aliasName);
        this.fileInfoService.updateFileInfo(fileInf);
        return AjaxResult.success();
    }

    @GetMapping("/resetFrontSource")
    @ApiOperation("清空来源设置")
    @ResponseBody
    public AjaxResult resetFrontSource(Long pageImgId) {
        FileInf fileInf = new FileInf();
        fileInf.setImgType(null);
        fileInf.setIsMaster(null);
        fileInf.setId(pageImgId);
        fileInf.setAliasName("");
        this.fileInfoService.updateFileInfo(fileInf);

        this.frontInterfaceFieldSourceService.deleteByPageImgId(pageImgId);
        return AjaxResult.success();
    }

    @GetMapping("/querySourceInterfaceContainCategory")
    @ApiOperation("来源接口的入参中包含类型")
    @ResponseBody
    public AjaxResult querySourceInterfaceContainCategory(Long pageId, Long interfaceId, Long sourcePageImgId) {
        Page page = this.pageService.selectPageById(pageId);
        Page page1 = new Page();
        page1.setCategoryId(page.getCategoryId());
        List<Page> pageList = this.pageService.selectPageList(page1);
        List<Long> pageIds = pageList.stream().map(Page::getId).collect(Collectors.toList());

        FrontInterfaceFieldSource frontInterfaceFieldSource = new FrontInterfaceFieldSource();
        frontInterfaceFieldSource.setSourceType("2");
        frontInterfaceFieldSource.setContractValueType("0");
        frontInterfaceFieldSource.setPageIds(pageIds);
        frontInterfaceFieldSource.setPageImgId(sourcePageImgId);
        frontInterfaceFieldSource.setInterfaceId(interfaceId);
        List<FrontInterfaceFieldSource> frontInterfaceFieldSources = this.frontInterfaceFieldSourceService.selectFrontInterfaceFieldSourceList(frontInterfaceFieldSource);
        if (CollectionUtil.isNotEmpty(frontInterfaceFieldSources)) {
            List<String> dictType= new ArrayList<>();
            for (FrontInterfaceFieldSource interfaceFieldSource : frontInterfaceFieldSources) {
                if (StringUtils.isNotEmpty(interfaceFieldSource.getDictType())) {
                    dictType.add(interfaceFieldSource.getDictType());
                }
            }
            if (dictType.size() > 0) {
                SysDictType dictType1 = new SysDictType();
                dictType1.setDictTypes(dictType);
                List<SysDictType> sysDictTypeList = this.sysDictTypeService.selectDictTypeList(dictType1);
                return AjaxResult.success(sysDictTypeList);
            }
        }
        return AjaxResult.success(new ArrayList<>());
    }

}
